import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/', // 网页打开第一次默认路由路径就是'/'
    component: () => import('@/views/layout'),
    redirect: '/home', // 重定向显示首页的二级路由
    children: [
      // 二级开始不用写/
      {
        path: 'home',
        component: () => import('@/views/home')
      },
      {
        path: 'user-info',
        component: () => import('@/views/user/userInfo.vue')
      },
      {
        path: 'user-avatar',
        component: () => import('@/views/user/userAvatar.vue')
      },
      {
        path: 'user-pwd',
        component: () => import('@/views/user/userPwd.vue')
      },
      {
        path: 'art-cate',
        component: () => import('@/views/article/artCate.vue')
      },
      {
        path: 'art-list',
        component: () => import('@/views/article/artList.vue')
      }
    ]
  },
  {
    path: '/reg',
    component: () => import('@/views/register')
  },
  {
    path: '/login',
    component: () => import('@/views/login')
  }
]

const router = new VueRouter({
  routes
})

// (白名单)无需登录可以访问的地址
const whiteList = ['/login', '/reg']

// 全局前置路由守卫
// 浏览器第一次打开项目页面,会触发一次全局前置路由守卫函数
// 有token就证明登陆了,无token未登录
router.beforeEach((to, from, next) => {
  const token = store.state.token
  if (token) {
    // 登陆了
    if (token && !store.state.userInfo.username) {
      // 如果本地有token,才去请求用户信息
      store.dispatch('getUserInfoActions')
    }
    next()
  } else {
    // 未登录
    // 数组.includes(值), 作用:判断值是否在数组里出现过,出现过原地返回true
    if (whiteList.includes(to.path)) {
      // 未登录,可以访问的路由地址,则放行(路由全局前置守卫不会再次触发了,而是匹配路由表,让组件挂载)
      next()
    } else {
      // next()强制切换到登录页面上
      next('/login')
    }
  }
})

export default router
